﻿IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[medianamik_IdentityGenerator]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[medianamik_IdentityGenerator](
	[Key] [varchar](200) NOT NULL,
	[Identity] [int] NULL,
	CONSTRAINT [PK_medianamik_IdentityGenerator] PRIMARY KEY CLUSTERED
	(
	[Key] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]	
END

/****** Object:  StoredProcedure [dbo].[medianamik_GetNextIdentityForKey]    Script Date: 03/08/2011 13:27:46 ******/
IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[medianamik_GetNextIdentityForKey]') AND type in (N'P', N'PC'))
BEGIN
	DECLARE @sqlProc nvarchar(2000)
	
	SET @sqlProc = '
	CREATE PROCEDURE [dbo].[medianamik_GetNextIdentityForKey]
	(
		@key Varchar(200),
		@startingValue int
	)
	AS
	--DECLARE @key Varchar(200),
	--		@startingValue int
			
	--SELECT	@key = ''Test'',
	--		@startingValue = 100

	SET NOCOUNT ON

	BEGIN TRAN

	IF NOT EXISTS(SELECT [Identity] FROM medianamik_IdentityGenerator WHERE [Key] = @key)
	BEGIN
		IF (@startingValue IS NULL)
		BEGIN
			SET @startingValue = 1
		END

		INSERT INTO medianamik_IdentityGenerator
		VALUES (@key, @startingValue)
		
	END
	ELSE
	BEGIN
		UPDATE	medianamik_IdentityGenerator 
		SET		[Identity] = [Identity] + 1
		WHERE	[Key] = @key
	END

	SELECT	[Identity] 
	FROM	medianamik_IdentityGenerator
	WHERE	[Key] = @key

	COMMIT TRAN'
	
	EXEC sp_executesql @sqlProc
END